<template>
  <div class="material-detail-list">
    <div class="table-operator" v-if="showOperator">
      <a-button type="primary" icon="plus" @click="handleAddDetail">添加明细</a-button>
      <a-button type="danger" icon="delete" @click="handleClearDetails" :disabled="detailList.length === 0">清空</a-button>
    </div>
    
    <a-table
      ref="detailTable"
      size="middle"
      bordered
      rowKey="id"
      :columns="detailColumns"
      :dataSource="detailList"
      :pagination="false"
      :scroll="{ y: tableHeight }">
      
      <template slot="materialTypeSlot" slot-scope="text">
        <j-dict-label :value="text" dictCode="material_type"/>
      </template>
      
      <template slot="materialSlot" slot-scope="text, record, index">
        <a-row>
          <a-col :span="20">
            <j-select-material
              v-model="record.materialCode"
              :type="record.materialType"
              @change="(value, materials) => handleDetailMaterialChange(value, materials, index)"
              placeholder="请选择物料"
              :disabled="disabled"
            />
          </a-col>
        </a-row>
      </template>
      
      <template slot="materialTypeSelectSlot" slot-scope="text, record, index">
        <j-dict-select-tag
          v-model="record.materialType"
          dictCode="material_type"
          placeholder="请选择物料类型"
          @change="(value) => handleDetailMaterialTypeChange(value, index)"
          :disabled="disabled"
        />
      </template>
      
      <template slot="quantitySlot" slot-scope="text, record">
        <a-input-number
          v-model="record.quantity"
          :min="0.01"
          :step="0.01"
          :precision="2"
          style="width: 100%"
          placeholder="请输入数量"
          :disabled="disabled"
        />
      </template>
      
      <template slot="remarkSlot" slot-scope="text, record">
        <a-input
          v-model="record.remark"
          placeholder="请输入备注"
          :disabled="disabled"
        />
      </template>
      
      <template slot="actionSlot" slot-scope="text, record, index">
        <a-button v-if="!disabled" type="danger" icon="delete" size="small" @click="removeDetail(index)">删除</a-button>
      </template>
    </a-table>
  </div>
</template>

<script>
  import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
  import JDictLabel from '@/components/dict/JDictLabel.vue'
  import JSelectMaterial from '@/components/jeecgbiz/JSelectMaterial'
  import { materialDetailList } from '@/api/wms'

  export default {
    name: 'MaterialDetailList',
    components: {
      JDictSelectTag,
      JDictLabel,
      JSelectMaterial
    },
    props: {
      materialId: {
        type: String,
        default: ''
      },
      value: {
        type: Array,
        default: () => []
      },
      disabled: {
        type: Boolean,
        default: false
      },
      showOperator: {
        type: Boolean,
        default: true
      },
      tableHeight: {
        type: Number,
        default: 300
      }
    },
    data() {
      return {
        detailList: [],
        detailColumns: [
          {
            title: '物料类型',
            align: 'center',
            dataIndex: 'materialType',
            width: 120,
            scopedSlots: { customRender: 'materialTypeSelectSlot' }
          },
          {
            title: '物料',
            align: 'center',
            dataIndex: 'materialCode',
            width: 200,
            scopedSlots: { customRender: 'materialSlot' }
          },
          {
            title: '物料名称',
            align: 'center',
            dataIndex: 'materialName',
            width: 150
          },
          {
            title: '规格',
            align: 'center',
            dataIndex: 'specification',
            width: 120
          },
          {
            title: '数量',
            align: 'center',
            dataIndex: 'quantity',
            width: 100,
            scopedSlots: { customRender: 'quantitySlot' }
          },
          {
            title: '单位',
            align: 'center',
            dataIndex: 'unit',
            width: 80
          },
          {
            title: '备注',
            align: 'center',
            dataIndex: 'remark',
            scopedSlots: { customRender: 'remarkSlot' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            width: 80,
            scopedSlots: { customRender: 'actionSlot' }
          }
        ]
      }
    },
    watch: {
      value: {
        immediate: true,
        handler(val) {
          if (val && val.length > 0) {
            this.detailList = [...val]
          }
        }
      },
      materialId: {
        immediate: true,
        handler(val) {
          if (val) {
            this.loadMaterialDetails()
          }
        }
      },
      detailList: {
        deep: true,
        handler(val) {
          this.$emit('input', val)
          this.$emit('change', val)
        }
      }
    },
    methods: {
      // 加载物料明细
      loadMaterialDetails() {
        if (!this.materialId) return
        
        materialDetailList(this.materialId).then(res => {
          if (res.success) {
            this.detailList = res.result || []
          }
        })
      },
      // 添加明细
      handleAddDetail() {
        this.detailList.push({
          id: this.generateTempId(),
          materialType: '',
          materialCode: '',
          materialName: '',
          specification: '',
          quantity: 1,
          unit: '',
          remark: ''
        })
      },
      // 移除明细
      removeDetail(index) {
        this.detailList.splice(index, 1)
      },
      // 清空明细
      handleClearDetails() {
        this.$confirm({
          title: '确认清空',
          content: '确定要清空所有组成明细吗？',
          okText: '确认',
          cancelText: '取消',
          onOk: () => {
            this.detailList = []
          }
        })
      },
      // 处理明细物料类型变化
      handleDetailMaterialTypeChange(value, index) {
        // 清空物料相关信息
        this.detailList[index].materialCode = ''
        this.detailList[index].materialName = ''
        this.detailList[index].specification = ''
        this.detailList[index].unit = ''
      },
      // 处理明细物料变化
      handleDetailMaterialChange(value, materials, index) {
        if (materials && materials.length > 0) {
          const material = materials[0]
          this.detailList[index].materialName = material.materialName
          this.detailList[index].specification = material.specification
          this.detailList[index].unit = material.unit
        }
      },
      // 生成临时ID
      generateTempId() {
        return 'temp_' + new Date().getTime() + '_' + Math.floor(Math.random() * 1000)
      }
    }
  }
</script>

<style scoped>
  .material-detail-list {
    width: 100%;
  }
  
  .table-operator {
    margin-bottom: 16px;
  }
  
  .table-operator button {
    margin-right: 8px;
  }
</style> 